package api

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"video-mgr/video-server/basic/inits"
	"video-mgr/video-server/basic/pkg"
)

func SendSms(c *gin.Context) {

	tel := c.Query("tel")

	if tel == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 0,
			"msg":  "手机号不能为空",
			"data": nil,
		})
	}

	countStr, err := inits.Rdb.Get(inits.Ctx, "sendSms").Result()
	if err != nil && err != redis.Nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 0,
			"msg":  "系统错误",
			"data": nil,
		})
		return
	}

	count := 0
	if countStr != "" {
		count, _ = strconv.Atoi(countStr)
	}

	if count >= 3 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 0,
			"msg":  "5分钟内最多发送3条验证码",
			"data": nil,
		})
		return
	}
	code := rand.Intn(900000) + 100000
	_, err = pkg.SendSms(tel, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 0,
			"msg":  "发送失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发送成功",
		"data": code,
	})
	inits.Rdb.Set(inits.Ctx, "sendSms", code, time.Minute*5)

	inits.Rdb.Incr(inits.Ctx, "sendSms")

	inits.Rdb.Expire(inits.Ctx, "sendSms", time.Minute*5)

}
